<template>
    <div class="main_container">
        <div v-if="pageName=='index'">
            <el-form :model="queryParams" label-width="auto">
                <el-row>
                    <el-col :span="7">
                        <el-form-item label="类型:">
                            <el-select style="width: 240px;" v-model="pageType" @change="typeChange"
                                placeholder="请选择">
                                <el-option  label="组装" value="join"></el-option>
                                <el-option  label="拆分" value="split"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="关键词:">
                            <el-input style="width: 240px;" maxlength="100" v-model="queryParams._search" placeholder="单据编号/商品名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="查询时间:">
                            <el-select style="width: 240px;" v-model="queryParams.date_order_type" placeholder="请选择" 
                                @change="dateChange" clearable>
                                <el-option v-for="item in queryTypes" :key="'pay_'+item.value" 
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button size="small" icon="el-icon-search" @click="handleQuery"
                            style="margin: 8px 0 0 20px;" class="btn_primary_color">查询</el-button>
                    </el-col>
                    <el-col :span="7" v-if="queryParams.date_order_type=='customize_date'">
                        <el-form-item label="自定义日期:">
                            <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                                v-model="queryParams.datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                                placeholder="请选择时间区间" style="width: 240px;" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-row :gutter="16" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    class="btn_primary_color"
                    icon="el-icon-plus"
                    size="small"
                    @click="handleAdd"
                    v-hasPermi="['stock_join_orders_add']"
                    >新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button
                    :class="multiple?'btn_info_color':'btn_remove_color'"
                    size="small"
                    icon="el-icon-delete"
                    @click="handleRemoveSelect"
                    :disabled="multiple"
                    v-hasPermi="['stock_join_orders_del']"
                    >删除所选</el-button>
                </el-col>
            </el-row>
            <el-table border :data="orderLists" style="margin-top: 15px;" @selection-change="handleSelectionChange" >
                <el-table-column type="selection" width="60" align="center" />
                <el-table-column label="单据编号" align="left" min-width="100" prop="corp_order_no" />
                <el-table-column label="组合件" v-if="pageType=='join'" align="left" prop="join_prods" />
                <el-table-column label="拆分件" v-else align="left" prop="split_prods" />
                <el-table-column label="子件" align="left" prop="sub_prods" />
                <el-table-column label="组装费用" v-if="pageType=='join'" align="left" prop="orders_fee_name" />
                <el-table-column label="拆分费用" v-else align="left" prop="orders_fee_name" />
                <el-table-column label="结算账户" align="left" prop="pay_type_str" />
                <el-table-column label="日期" align="left" prop="orders_date" />
                <el-table-column label="操作" min-width="70" align="left" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleView(scope.row)"
                            style="font-weight: bold;"
                        >查看</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="handleRemove(scope.row)"
                            style="font-weight: bold;"
                            v-hasPermi="['stock_join_orders_del']"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="getJoinSplitLists"
                @current-change="getJoinSplitLists"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增页面 -->
        <common-dialog :visiable="pageName == 'addOrder'">
            <add-order :corpId="corp_id" @hidden="hidden" @success="success"></add-order>
        </common-dialog>
        <!-- 查看页面 -->
        <common-dialog :visiable="pageName == 'queryOrder'">
            <query-order :corpId="corp_id" :editId="editId" :type="pageType" @hidden="hidden"></query-order>
        </common-dialog>
    </div>
</template>

<script>
import commonDialog from "@/components/commonDialog";
import { listJoin, listSplit, removeJoin, removeSplit } from "@/api/joinsplit";

export default {
    name: 'joinSplit',
    data() {
        return {
            showExpendInfo: false,
            corp_id: '',
            editId: '',
            multiple: true,
            queryParams: {
                _search: '',
                datetime: [],
                date_order_type: 'cur_month',
                start_date: '',
                end_date: '',
            },
            pageParam: {
                page: 1,
                num: 10
            },
            pageName: 'index',
            total: 0,
            orderLists: [],
            pageType: 'join',
            typeList: [],
            queryTypes: [
                {label: '今日', value: 'cur_day'},
				{label: '本周', value: 'cur_weak'},
				{label: '本月', value: 'cur_month'},
				{label: '本年', value: 'cur_year'},
				{label: '自定义', value: 'customize_date'}
            ],
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            viewForm: {}
        }
    },
    watch: {
        'queryParams.datetime': {
            handler(value){
                if(value){
                    this.queryParams.start_date = value[0]
                    this.queryParams.end_date = value[1]
                }
                else{
                    this.queryParams.start_date = this.queryParams.end_date = null
                }
            },
            deep: true
        },
        '$route.query.bussId4': {
            immediate: true, // 首次加载时触发
            handler(newId) {
                if (newId) {
                    this.pageName = 'queryOrder'
                    this.editId = null
                }
            }
        }
    },
    components: {
        commonDialog,
        addOrder: () => import('./edit.vue'),
        queryOrder: () => import('./query.vue')
    },
    created() {
        this.corp_id = this.$store.state.corpId
        this.getJoinSplitLists()
    },
    methods: {
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.getJoinSplitLists()
        },
        typeChange() {
            this.pageParam.page = 1
            this.getJoinSplitLists()
        },
        dateChange(val) {
            this.queryParams.date_order_type = val
            this.queryParams.start_date = ''
            this.queryParams.end_date = ''

            if (val == 'customize_date'){
                return
            }
            let nowDate = new Date()
            switch (val){
                case 'cur_year':
                    this.queryParams.start_date = nowDate.getFullYear()+'-01-01'
                    break;
                case 'cur_month':
                    this.queryParams.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-01'
                    break;
                default:
                    break;
            }
            
        },
         // 获取列表
        getJoinSplitLists() {
            this.queryParams.corp = this.corp_id
            let params = Object.assign({}, this.queryParams, this.pageParam)
            let temp = null
            if (this.pageType == 'join'){
                temp = listJoin(params)
            }else {
                temp = listSplit(params)
            }
            let that = this
            temp.then(res => {
                that.orderLists = res.data.data.orders_list.filter(item => {
                    item.orders_fee_name = '￥'+item.orders_fee
                    item.pay_type_str = item.pay_type===0 ? '' : item.pay_type_str
                    let joins = [], splits = [], join_subs = [], split_subs = [];
                    item.orders_goods_detail.forEach(_item => {
                        if (that.pageType == 'join'){
                            if (_item.num_type === 1){  //入库,组合件
                                joins.push(_item.goods_details.name)
                            }else{
                                join_subs.push(_item.goods_details.name)
                            }
                        }else{
                            if (_item.num_type === 1){  //入库,子件
                                split_subs.push(_item.goods_details.name)
                            }else{
                                splits.push(_item.goods_details.name)
                            }
                        }
                    })
                    item.join_prods = joins.join('、')
                    item.split_prods = splits.join('、')
                    item.sub_prods = join_subs.length ? join_subs.join('、') : split_subs.join('、')
                    return item
                })
                that.total = res.data.data.total
            })
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            // console.log(selection);
            this.multiple = !selection.length
            let ids = selection.map(item => item.id)
            this.selectIds = ids
        },
        // 新增
        handleAdd() {
            this.editId = null
            this.pageName = 'addOrder'
        },
        // 查看
        handleView(item) {
            this.editId = item.id
            this.pageName = 'queryOrder'
        },
        // 编辑
        handleEdit(item) {
            this.editId = item.id
            this.pageName = 'editOrder'
        },
        // 删除所选
        handleRemoveSelect() {
            let that = this
            this.$confirm('您确定要删除选中的销售单吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeBatchExpend({
                    corp_id: that.corp_id,
                    pk_id_list: that.selectIds
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 删除
        handleRemove(item) {
            let that = this
            let type = this.pageType=='join' ? '组装单' : '拆分单'
            this.$confirm('您确定要删除该'+type+'吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let temp = that.pageType=='join' ? removeJoin(item.id, {corp: that.corp_id}) : removeSplit(item.id, {corp: that.corp_id})
                temp.then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        hidden() {
            this.pageName = 'index'
            if (this.$route.query.bussId4){
                this.$router.replace({ path: this.$route.path, query: {} });
            }
        },
        success() {
            this.handleQuery()
            this.pageName = 'index'
        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .cates_view {
        padding: 0 30px 30px 30px;
        .tops {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .list {
            margin-top: 28px;
            .cell {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                font-size: 14px;
                border-bottom: 1px solid #eee;
                .btns {
                    display: inline-flex;
                    align-items: center;
                    height: 100%;
                    span {
                        width: 50px;
                        text-align: center;
                        color: @blue;
                        font-size: 13px;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }
</style>